package com.bl.car.controller;

import com.bl.car.constants.StateConstant;
import com.bl.car.entity.Driver;
import com.bl.car.entity.Owner;
import com.bl.car.repositiy.DriverRepository;
import com.bl.car.repositiy.OwnerRepository;
import com.bl.car.result.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 驾驶员对外接口
 *
 * @author zhx
 * @create 2017-11-16 11:34
 **/
@RestController
@RequestMapping("/driver")
public class DriverController {

    @Autowired
    private DriverRepository driverRepository;

    @Autowired
    private OwnerRepository ownerRepository;


    //获取要注销的驾驶员
    @PostMapping("/deldriver")
    public Result<List<Driver>> deldriver(){
        List<Driver> byDriverId = driverRepository.findByIsEffect(StateConstant.DELETE_TYPE);

        return Result.ok(byDriverId);

    }

    //取列表
    @PostMapping("/getMyDriverList")
    public Result<List<Driver>> getMyDriverList(@RequestParam("userId") String userId,@RequestParam("name") String name){
        //获取的是  userid
        Owner byUserId = ownerRepository.findByUserId(userId);


        List<Driver> byOwnerIdOrderById = new ArrayList<>();

        if(StringUtils.isEmpty(name)){
            byOwnerIdOrderById = driverRepository.findByOwnerIdOrderById(Long.toString(byUserId.getId()));
        }else{
            byOwnerIdOrderById = driverRepository.findByOwnerIdAndNameLikeOrderById(Long.toString(byUserId.getId()),name);
        }


        return Result.ok(byOwnerIdOrderById);

    }


    //取单个驾驶员getDriverDetail
    @PostMapping("/getDriverDetail")
    public Result<Driver> getDriverDetail(@RequestParam("id") Long id){
        Driver byOwnerIdOrderById = driverRepository.findOne(id);

        return Result.ok(byOwnerIdOrderById);

    }

    //根据用户id取单个驾驶员
    @PostMapping("/getDriverDetailByUser/{id}")
    public Result<Driver> getDriverDetailByUser(@PathVariable("id") String id){
        Driver byOwnerIdOrderById = driverRepository.findByUserId(id);

        return Result.ok(byOwnerIdOrderById);

    }

    //保存saveDriver
    @PostMapping("/saveDriver/{id}")
    public Result<Driver> saveDriver(@RequestBody Driver driver,@PathVariable("id") String id){
        if(driver.getId()==null){
            //新增
            System.out.println("新增驾驶员");

            driver.setOwnerId(id);

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            driver.setApplyTime(df.format(new Date()));
            driver.setIsEffect(StateConstant.USER_CHECK);
            driverRepository.save(driver);

            return Result.ok(driver);
        }else{
            driverRepository.save(driver);
            return Result.ok(driver);
        }
    }

}
